﻿using DatabaseModel;
using LogBookImporter.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LogBookImporter.Extensions;
using System.Data.Entity.Validation;

namespace LogBookImporter.Implementation {
    public class LogBookImporter {

        /// <summary>
        /// Imports Logbook entries into the database specified in the App.config file.
        /// </summary>
        /// <param name="basePath">The path where to begin to search for logbooks</param>
        /// <param name="logfilePath">The log file path including the filename</param>
        /// <returns></returns>
        public int Import(string basePath, string logfilePath) {
            int entriesImported = 0;
            LogBookReader reader = new LogBookReader();
            LogBookEntryCreator creator = new LogBookEntryCreator();
            LogBookEntryRepository repository = new LogBookEntryRepository();
            List<string> fileLocationsToParse = LogBookCrawler.Crawl(basePath);
            Logger.Logger logger = new Logger.Logger(logfilePath);
            try {
                    logger.Start("Logbook import");
                    foreach (string fileLocation in fileLocationsToParse) {
                        List<string> logBookContent = reader.ReadLogBook(fileLocation);
                        List<LogBookEntry> logBookEntries = new List<LogBookEntry>();

                        logBookEntries = creator.CreateLogBookEntries(logBookContent, logger, fileLocation);
                        

                        try {
                            entriesImported += repository.InsertLogBookEntries(logBookEntries);
                        }
                        catch (DbEntityValidationException exception) {
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.AppendLine(string.Format("Error inserting logbook entry object into the database for file {0}. Exception: {1}", fileLocation, exception.GetaAllMessages()));
                            foreach (var eve in exception.EntityValidationErrors) {
                                stringBuilder.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                    eve.Entry.Entity.GetType().Name, eve.Entry.State));
                                foreach (var ve in eve.ValidationErrors) {
                                    stringBuilder.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                        ve.PropertyName, ve.ErrorMessage));
                                }
                            }

                            logger.Log(stringBuilder.ToString());
                        }
                        catch (Exception exception) {
                            logger.Log(string.Format("Error inserting logbook entry object into the database for file {0}. Exception: {1}", fileLocation, exception.GetaAllMessages()));
                        }
                }
                
            }
            catch (Exception exception) {
                logger.Log(exception.GetaAllMessages());
            }
            finally {
                logger.Dispose();
            }



            return entriesImported;
        }
    }
}
